<template>
  <div>
    <!-- :model="form"  -->
    <el-form ref="form" label-width="80px" inline style="margin: 10px 0px">
      <el-form-item>
        <el-input placeholder="用户名" v-model="searchObj.username"></el-input>
      </el-form-item>
      <el-button type="primary" icon="el-icon-zoom-in" @click="searchUsername"
        >查询</el-button
      >
      <el-button @click="clearUserName">清空</el-button>
    </el-form>
    <el-button type="primary" @click="dialogVisible = true">添加</el-button>
    <el-button
      type="danger"
      @click="deleteHandle"
      :disabled="!this.SelectionId.length"
      >批量删除</el-button
    >

    <el-table
      style="width: 100%"
      :data="userData"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="width" align="center">
      </el-table-column>
      <el-table-column type="index" label="序号" width="width" align="center">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="width">
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" width="width">
      </el-table-column>
      <el-table-column prop="roleName" label="权限列表" width="width">
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="width">
      </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间" width="width">
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template v-slot="{ row, $index }">
          <el-button
            type="info"
            icon="el-icon-info"
            size="mini"
            @click="seeRoleInfo(row)"
          ></el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editbutton(row)"
          ></el-button>
          <el-popconfirm title="你确定删除吗？" @onConfirm="deleteUser(row)">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              slot="reference"
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="getUserDate"
      :current-page="currentPage"
      :page-sizes="[3, 5, 10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      align="center"
    >
    </el-pagination>
    <el-dialog
      :title="userInfo.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        label-width="80px"
        :model="userInfo"
        :rules="rules"
        ref="userform"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="nickName">
          <el-input v-model="userInfo.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userInfo.id">
          <el-input v-model="userInfo.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelhendle">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="设置角色" :visible.sync="dialogVisible2" width="50%">
      <el-form ref="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="checkedrolesId"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-for="(role, index) in allroles"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="doneroles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dayjs, { isDayjs } from "dayjs";
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "user",
  data() {
    //!!进行表单验证
    var validateFrom = (rule, value, callback) => {
      // console.log(rule);
      // console.log(value);
      // console.log(callback);
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      userData: [],
      currentPage: 1,
      pageSize: 3,
      total: 30,
      searchObj: {
        username: "",
      },
      userInfo: {
        deleted: false,
        gmtCreate: "",
        gmtModified: "",
        nickName: "",
        password: "",
        username: "",
        salt: "",
        token: "",
      },
      dialogVisible: false,
      dialogVisible2: false,
      SelectionId: [],
      allroles: [],
      checkedrolesId: [],
      checkAll: false,
      isIndeterminate: true,
      //!!进行表单验证
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 4, message: "用户名不能小于4位" },
          { validator: validateFrom, trigger: "change" },
        ],
        nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getUserDate();
  },
  methods: {
    //得到用户数据
    async getUserDate(page = 1) {
      this.currentPage = page;
      this.loading = true;
      let { pageSize, currentPage, searchObj } = this;
      const result = await this.$API.user.getPageList(
        currentPage,
        pageSize,
        searchObj
      );
      // console.log(result);
      if (result.code == 20000) {
        this.loading = false;
        this.userData = result.data.items;
        this.total = result.data.total;
      }
    },
    //改变当前页面显示的信息条数
    handleSizeChange(limit) {
      this.pageSize = limit;
      this.getUserDate(this.currentPage);
    },
    //清空搜索用户名
    clearUserName() {
      this.searchObj.username = "";
      this.getUserDate();
    },
    //搜索用户名
    searchUsername() {
      this.getUserDate();
    },
    // 添加用户操作或者修改用户操作
    addUser() {
      //!!进行表单验证
      this.$refs.userform.validate(async (success) => {
        if (success) {
          console.log(success);
          let { userInfo } = this;
          //!!这里不需要填写时间信息发送给后端  这里后端自己自己写好了时间  工作中需要好后端沟通好!!!!
          // this.userInfo.gmtCreate = dayjs().format("YYYY-MM-DD HH:mm:ss");
          // this.userInfo.gmtModified = dayjs().format("YYYY-MM-DD HH:mm:ss");
          let result = await this.$API.user[userInfo.id ? "update" : "add"](
            userInfo
          );
          // console.log(result);
          if (userInfo.id) {
            if (result.code == 20000) {
              //修改一个用户
              this.dialogVisible = false;
              this.$message({ message: "修改成功", type: "success" });
              this.getUserDate(this.page);
              this.userInfo = {};
            }
          } else {
            if (result.code == 20000) {
              //添加一个用户
              this.dialogVisible = false;
              this.$message({ message: "添加成功", type: "success" });
              this.getUserDate();
              this.userInfo = {};
            }
          }
        } else {
          return false;
        }
      });
    },
    //点击修改按钮操作
    async editbutton(user) {
      this.dialogVisible = true;
      this.userInfo = cloneDeep(user);
    },
    //取消操作
    cancelhendle() {
      this.dialogVisible = false;
      this.userInfo = {};
    },
    //删除用户
    async deleteUser(row) {
      let result = await this.$API.user.removeById(row.id);
      // console.log(result);
      if (result.code == 20000) {
        this.getUserDate(this.currentPage);
      }
    },
    //当选择项发送变化时  储存变化的选项
    handleSelectionChange(rows) {
      // console.log(rows);
      this.SelectionId = rows.map((item) => {
        return item.id;
      });
    },
    //批量删除用户
    deleteHandle() {
      this.$confirm("此操作将永久删除用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // console.log(this.SelectionId);
          let result = await this.$API.user.removeUsers(this.SelectionId);
          console.log(result);
          if (result.code == 20000) {
            this.getUserDate();
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //查看用户的角色信息
    async seeRoleInfo(row) {
      this.dialogVisible2 = true;
      this.userInfo.id = row.id;
      this.userInfo.username = row.username;
      let result = await this.$API.user.getRoles(row.id);
      console.log(result);
      if (result.code == 20000) {
        this.allroles = result.data.allRolesList;
        this.checkedrolesId = result.data.assignRoles.map((element) => {
          return element.id;
        });
        this.checkAll = this.allroles.length === this.checkedrolesId.length;
        this.isIndeterminate =
          this.checkedrolesId.length > 0 &&
          this.checkedrolesId.length < this.allroles.length;
      }
    },
    //全选按钮改变时
    handleCheckAllChange(value) {
      console.log(value);
      this.checkedrolesId = value ? this.allroles.map((item) => item.id) : [];
      // 如果当前不是全选也不全不选时, 指定为false
      this.isIndeterminate = false;
    },
    //不同角色选择框变化时
    handleCheckedChange(value) {
      this.checkedrolesId = value;
      // console.log(value);
    },
    //确定绑定不同用户新的角色
    async doneroles() {
      this.dialogVisible2 = false;
      let result = await this.$API.user.assignRoles(
        this.userInfo.id,
        this.checkedrolesId.toString()
      );
      // console.log(result);
      this.getUserDate(this.currentPage);
      this.$message.success(result.message || "分配角色成功");
    },
  },
};
</script>

<style>
</style>